<template>
  <div>
    <input
      type="file"
      @change="handleFileChange"
      accept="video/*"
    />
    <textarea
      v-model="text"
      rows="4"
      cols="50"
    ></textarea>
    <button @click="startUpload">开始上传</button>
    <el-progress :percentage="uploadProgress"></el-progress>
    <div>{{ message }}</div>
  </div>
</template>

<script>
export default {
  name: "test",
  data() {
    return {
      file: null,
      text: "",
      chunkSize: 1024 * 1024, // 1MB 分片大小
      totalChunks: 0,
      uploadedChunks: 0,
      uploadProgress: 0,
      message: "",
    };
  },
  methods: {
    // 选择文件
    handleFileChange(event) {
      this.file = event.target.files[0];
      console.log(this.file);
    },
    // 开始上传 所有需要上传的文字和文件放到一个formData对象中
    async startUpload() {
      if (!this.file) {
        this.message = "请选择一个视频文件";
        return;
      }

      this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
      this.uploadedChunks = 0;

      const formData = new FormData();
      formData.append("text", this.text);
      formData.append("file", this.file);
      formData.append("totalChunks", this.totalChunks);

      const startChunkNumber = 0;
      await this.uploadChunks(formData, startChunkNumber);
    },
    // 分片上传
    async uploadChunks(formData, startChunkNumber) {
      let chunkNumber = startChunkNumber;
      this.uploadedChunks = startChunkNumber;

      const uploadChunk = async (chunkNumber) => {
        const start = chunkNumber * this.chunkSize;
        const end = Math.min(start + this.chunkSize, this.file.size);
        const chunk = this.file.slice(start, end);

        formData.set("chunkNumber", chunkNumber);
        formData.set("chunk", chunk);

        try {
          const response = await this.uploadChunk(formData);

          if (response.status === 200) {
            this.uploadedChunks++;
            this.uploadProgress =
              (this.uploadedChunks / this.totalChunks) * 100;
            this.message = `已上传 ${this.uploadedChunks} / ${this.totalChunks} 分片`;

            if (chunkNumber < this.totalChunks - 1) {
              // 继续上传下一个分片
              uploadChunk(chunkNumber + 1);
            } else {
              this.message = "上传完成";
            }
          } else {
            this.message = "文件上传失败";
          }
        } catch (error) {
          console.error("上传错误:", error);
          this.message = "文件上传失败";
        }
      };

      uploadChunk(chunkNumber);
    },
    // 上传
    async uploadChunk(formData) {
      // 使用 Axios 或其他 HTTP 客户端库将分片数据上传到后端
    },
  },
};
</script>
